<template>
  <Drawer
      title="审核"
      v-model="show"
      :width="width"
      :mask-closable="false"
      @on-close="closeWin"
      :styles="{height: 'calc(100% - 55px)',overflow: 'auto',paddingBottom: '53px',position: 'static'}">

    <slot :row="props.row"></slot>
    <Form ref="validForm" :model="formData" :rules="ruleValidate">
      <FormItem label="状态" label-position="top" prop="state" :error="error.state">
        <RadioGroup v-model.number="formData.state">
          <Radio :label="1">通过</Radio>
          <Radio :label="-1">不通过</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem v-if="formData.state == -1" label="审核未通过原因" label-position="top" prop="reason"
                :error="error.reason">
        <Input type="textarea" v-model="formData.reason" :rows="4" placeholder="请输入审核未通过原因"/>
      </FormItem>
    </Form>

    <div class="demo-drawer-footer">
      <Button style="margin-right: 8px" @click="closeWin">关闭</Button>
      <Button type="primary" :loading="loading" @click="handleForm">保存</Button>
    </div>
  </Drawer>
</template>

<script setup>

import {ref, reactive} from 'vue'
import RSS from "../api/rssIndex.js";

const props = defineProps({
  modelValue: {
    type: Boolean, required: true
  },
  row: {
    type: Object, required: true,
  },
  width: {
    type: Number, required: false, default: 720
  }
});

const loading = ref(false); // 加载状态

const show = ref(props.modelValue); // 窗口的状态

const formData = ref({
  reason: props.row.reason,
  id: props.row.id,
  state: props.row.state == 0 ? null : props.row.state
});

const ruleValidate = reactive({
  reason: [
    {required: true, message: "原因不能为空", trigger: "blur"},
    {type: "string", max: 50, message: "原因不能超过50个字符", trigger: "blur"},
  ],
  state: [
    {required: true, type: "integer", message: "必须选择审核状态", trigger: "change"},
  ]
});

const emits = defineEmits(["update:model-value", "on-verify"]);

const validForm = ref(null);

const error = ref({});  // 定义后端接口返回的错误信息

function handleForm() {
  loading.value = true;
  error.value = {}; // 重置错误消息
  validForm.value.validate(valid => {
    if (valid) {
      RSS.auditeResource({id: formData.value.id, state: formData.value.state, reason: formData.value.reason}).then(ret=> {
         if (ret.status) {
           // 保存数据， 成功后，关闭 loading
           emits("on-verify", {...formData.value});
         }
      })
    }
    loading.value = false;
  })
}

function closeWin() {
  show.value = false;
  emits("update:model-value", show.value);
  validForm.value.resetFields();
  error.value = {};
}

</script>

<style>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>